<template>
	<view class="app login">
		<view class="title" style="padding-top: 100rpx">
			<u-icon
				style="margin: 0 0 24rpx"
				name="arrow-leftward"
				v-if="flag"
				@tap="navBack"
			></u-icon>
			<text>欢迎登录！</text>
			<text class="sub">请输入手机号密码登录</text>
		</view>
		<view class="content" v-if="['pwd', 'sms'].indexOf(loginWay) > -1">
			<swiper
				style="height: 300rpx"
				duration="200"
				disable-touch
				:current="loginWay == 'pwd' ? 0 : 1"
			>
				<swiper-item>
					<view class="form-view">
						<view class="form-item form-border">
							<input
								placeholder-style="'color':'#8e8e8e'"
								placeholder="用户名/手机号"
								v-model="form1.username"
								class="form-input"
								type="text"
								:maxlength="50"
							/>
						</view>
						<view class="form-item form-border">
							<input
								placeholder-style="'color':'#8e8e8e'"
								v-model="form1.password"
								class="form-input"
								placeholder="密码"
								type="password"
								:maxlength="50"
							/>
						</view>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="form-view">
						<view class="form-item form-border">
							<input
								placeholder-style="'color':'#8e8e8e'"
								v-model="form1.mobile"
								placeholder="手机号"
								class="form-input"
								type="text"
								:maxlength="50"
							/>
						</view>
						<view class="form-item form-border">
							<input
								placeholder-style="'color':'#8e8e8e'"
								placeholder="请输入短信验证码"
								v-model="form1.code"
								class="form-input"
								type="number"
								:maxlength="6"
							/>
							<vk-data-verification-code
								custom-style="font-size: 28rpx;"
								seconds="60"
								type="login"
								:mobile="form1.mobile"
								:check-user-exist="true"
								@error="codeError"
							></vk-data-verification-code>
						</view>
					</view>
				</swiper-item>
			</swiper>
			<view class="login-way-change">
				<label
					v-if="loginWay == 'pwd'"
					class="login-way-left"
					@click="savePwd = !savePwd"
				>
					<checkbox
						active-color="#737373"
						class="checkbox"
						shape="circle"
						:checked="savePwd"
					></checkbox>
					<text>记住密码</text>
				</label>
				<view class="login-way-right">
					<text v-if="loginWay == 'pwd'" @click="loginWay = 'sms'">切换验证码登录</text>
					<text v-if="loginWay == 'sms'" @click="loginWay = 'pwd'">切换账号密码登录</text>
				</view>
			</view>
			<view class="tips">
				<navigator url="./forget" open-type="navigate" style="margin-left: 20rpx">
					找回密码
				</navigator>
				<text class="center-line"> | </text>
				<navigator url="./register" open-type="navigate">注册账号</navigator>
			</view>
			<view class="submit-btn">
				<button
					class="btn success circle"
					hover-class="hover"
					shape="circle"
					type="success"
					:plain="false"
					:hair-line="false"
					:disabled="loading"
					@click="login"
				>
					登 录
				</button>
				<!-- 其他登录 -->
				<button
					class="btn circle wx"
					hover-class="hover"
					shape="circle"
					type="success"
					:plain="false"
					:hair-line="false"
					:disabled="loading"
					@click="loginWay = 'onekey'"
				>
					<u-icon name="weixin-fill" color="#19be6b" size="50"></u-icon>
					<text style="margin-left: 6rpx">微信一键登录</text>
				</button>
			</view>
		</view>
		<!-- 一键登录 -->
		<view class="content" v-else-if="['onekey'].indexOf(loginWay) > -1">
			<!-- 头部logo -->
			<view class="header">
				<image class="logo" :src="logoImage"></image>
			</view>
			<view class="submit-btn">
				<button
					class="btn success circle"
					hover-class="hover"
					shape="circle"
					type="success"
					:plain="false"
					:hair-line="false"
					:disabled="loading"
					@click="loginWeixin"
				>
					微信一键登录
				</button>
			</view>
			<!-- 密码和短信登录方式的切换 -->
			<view class="login-way-change" style="margin-top: 60rpx">
				<view class="login-way-right">
					<text @click="loginWay = 'pwd'">切换账号密码登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
var vk = uni.vk // vk依赖

export default {
	data() {
		return {
			// init请求返回的数据
			data: {},
			// 表单请求数据
			form1: {
				username: "", // 账号
				password: "", // 密码
				mobile: "", // 手机号
				code: "", // 短信验证码
				inviteCode: "" // 邀请码
			},
			loginWay: "onekey", // 登录方式 pwd：账号+密码登录 sms：手机+短信登录
			savePwd: true, // 是否记住密码
			platform: "", // 平台信息
			envH5: "",
			h5WeixinAppId: "",
			loading: false,
			showLogin: false,
			// 其他登录方式 onekey 一键登录 weixin 微信登录
			loginMode: ["weixin"],
			logoImage: "/static/logo.png",

			flag: false,
			back: false
		}
	},
	onLoad(options) {
		let pages = getCurrentPages()
		if (
			pages.length >= 2 &&
			pages[pages.length - 2].route &&
			pages[pages.length - 2].route.indexOf("login") == -1
		) {
			this.flag = true
		} else {
			this.flag = false
		}
		let logo = vk.getVuex("$user.mchInfo.logo")
		if (logo) this.logoImage = logo

		this.init(options)
	},
	onShow() {
		// #ifdef MP-WEIXIN
		uni.hideHomeButton()
		// #endif
		if (vk.checkToken() && this.back) {
			this.back = false
			vk.navigateToHome()
		}
	},
	methods: {
		navBack() {
			uni.navigateBack()
		},
		// 页面数据初始化函数
		init(options = {}) {
			let that = this
			console.log("init: ", options)
			that.platform = vk.pubfn.getPlatform()
			// #ifdef H5
			that.envH5 = vk.h5.getEnv()
			if (that.envH5 === "h5-weixin" && options.code) {
				that.loginWeixinH5(options)
			}
			// #endif
			// #ifdef MP
			// 需要先在onLoad内执行此函数
			vk.userCenter.code2SessionWeixin({
				loading: true,
				data: {
					needCache: true
				},
				success: data => {
					that.encryptedKey = data.encryptedKey
					that.showLogin = true
				}
			})
			// #endif
			that.form1.inviteCode = vk.getVuex("$user.inviteCode")
			let username = vk.getVuex("$user.login.username")
			let password = vk.getVuex("$user.login.password")
			let savePwd = vk.getVuex("$user.login.savePwd")
			let mobile = vk.getVuex("$user.login.mobile")
			if (username) that.form1.username = username
			if (password) that.form1.password = password
			if (mobile) that.form1.mobile = mobile
			if (typeof savePwd === "boolean") {
				that.savePwd = savePwd
			}

			that.loginWay = "onekey"
		},
		// 账号密码登录
		login() {
			// 防抖函数
			let that = this
			vk.pubfn.debounce(() => {
				let { loginWay, form1 } = that
				if (loginWay === "pwd") {
					that.loginByPwd()
				} else if (loginWay === "sms") {
					that.loginBySms()
				}
			}, 500)
		},
		// 手机短信登录
		loginBySms() {
			let that = this
			let { form1 } = that
			let { mobile, code, inviteCode } = form1
			if (!vk.pubfn.checkStr(mobile, "mobile")) {
				return vk.toast("手机号格式错误")
			}
			if (!code) {
				return vk.toast("请输入验证码")
			}
			vk.userCenter.loginBySms({
				data: { inviteCode, mobile, code, type: "login" },
				success: data => {
					vk.setVuex("$user.login.mobile", mobile)
					vk.toast("登陆成功!", 600, () => {
						// 跳转到首页,或页面返回
						that.loginSuccess(data)
					})
				}
			})
		},
		// 账号密码登录
		loginByPwd() {
			let that = this
			let { form1, savePwd } = that
			let { username, password } = form1
			if (username.length < 4) {
				return vk.toast("账号至少4位数")
			}
			if (!vk.pubfn.checkStr(password, "pwd")) {
				return vk.toast("密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线")
			}
			// 登录操作
			vk.userCenter.login({
				data: { username, password },
				//loading:false,
				success: data => {
					vk.toast("登陆成功!", 600, () => {
						// 跳转到首页,或页面返回
						if (savePwd) {
							vk.setVuex("$user.login.username", username)
							vk.setVuex("$user.login.password", password)
						} else {
							vk.setVuex("$user.login.password", "")
						}
						vk.setVuex("$user.login.savePwd", savePwd)
						that.loginSuccess(data)
					})
				}
			})
		},
		// 登录成功后的执行逻辑
		loginSuccess(data) {
			let that = this
			// 检查是否有指定跳转的页面
			let app = getApp()
			if (typeof app.init == "function") app.init()
			if (vk.navigate.originalPage) {
				vk.navigate.originalTo()
				return false
			}
			if (that.envH5 === "h5-weixin") {
				return this.getH5WeixinCode()
			}
			// 跳转到首页,或页面返回
			let pages = getCurrentPages()
			if (
				pages.length >= 2 &&
				pages[pages.length - 2].route &&
				pages[pages.length - 2].route.indexOf("login") == -1
			) {
				const eventChannel = that.getOpenerEventChannel()
				eventChannel.emit("loginSuccess", {})
				// 页面返回
				vk.navigateBack()
			} else {
				// 进入首页
				vk.navigateToHome()
			}
		},
		// 第三方登录 - 微信
		loginWeixin() {
			// #ifdef APP-PLUS
			vk.userCenter.loginByWeixin({
				success: res => {
					if (res.mobileConfirmed) {
						return this.loginSuccess()
					}
					this.back = true
					vk.toast("未绑定手机号，请前往绑定", "none", 1300, () => {
						vk.reLaunch("/pages/user/setting/update-mobile?pageIndex=1&from=log")
					})
				}
			})
			// #endif
			// #ifdef H5
			let appid = vk.getVuex("$app.config.service.h5weixin.appid")
			let scope = "snsapi_base"
			let redirect_uri = window.location.href.split("?")[0];
			if (!redirect_uri) {
				let splitArr = window.location.href.split("/")
				let serviceUrl = splitArr[0] + "//" + splitArr[2]
				redirect_uri = `${serviceUrl}/pages/login/h5-weixin-auth`
				vk.setStorageSync("vkmall.h5-weixin-auth-redirect-uri", window.location.href)
			}
			let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=login#wechat_redirect`
			window.location.href = url
			// #endif
		},
	  
		// 第三方登录 - 微信H5
		loginWeixinH5(opt) {
			vk.userCenter.loginByWeixin({
				data: { code: opt.code, nickname: "微信用户" },
				success: res => {
					if (res.mobileConfirmed) {
						return this.loginSuccess()
					}
					this.back = true
					vk.toast("未绑定手机号，请前往绑定", "none", 1300, () => {
						vk.reLaunch("/pages/user/setting/update-mobile?pageIndex=1&from=log")
					})
				}
			})
		},
		// 微信公众号授权登录
		getH5WeixinCode() {
			let appid = vk.getVuex("$app.config.service.h5weixin.appid")
			let scope = "snsapi_base"
			let redirect_uri = window.location.href.split("?")[0];
			//截取到主域名 "https://www.a.net/pages/login/register
			redirect_uri = this.getPrefix(redirect_uri)
			let url =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=login#wechat_redirect`
			window.location.href = url
		},
		codeError(res) {
			if (res.notExists) {
				let mobile = this.form1.mobile
				vk.navigateTo(`./register?mobile=${mobile}`)
			}
		},
		getPrefix(url) {
			let parts = url.split('/');
			let index = parts.indexOf('pages');
			if (index !== -1) {
				return parts.slice(0, index).join('/');
			} else {
				return url;
			}
		},
	}
}
</script>

<style lang="scss" scoped>
@import url("./css/main.css");

.login {
	height: 100vh;
	background-color: #f5f5f5;
}

.back_icon {
	position: absolute;
	top: 20rpx;
	left: 16rpx;
}

.login-way-change {
	display: flex;
	padding: 0 48rpx 0 40rpx;
	align-items: center;
	height: 50rpx;

	.login-way-left {
		.checkbox {
			transform: scale(0.7);
		}
	}

	.login-way-right {
		flex: 1;
		text-align: right;
	}
}

.tips {
	display: flex;
	justify-content: flex-end;
	padding: 10rpx 48rpx;
	color: #24c388;

	.center-line {
		margin: 0 8rpx;
	}
}

.invite-code-popup {
	padding: 50rpx;

	.invite-code-popup-title {
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
	}

	.invite-code-popup-input-border {
		margin-top: 50rpx;
		border: none;
		border-radius: 2.5rem;
		-webkit-box-shadow: 0 0 60rpx 0 rgba(43, 86, 112, 0.1);
		box-shadow: 0 0 60rpx 0 rgba(43, 86, 112, 0.1);

		.invite-code-popup-input {
			flex: 1;
			text-align: left;
			font-size: 28rpx;
			padding: 0 40rpx;
			width: 100%;
			height: 100rpx;
			box-sizing: border-box;
		}
	}

	.bind-btn {
		margin-top: 60rpx;
	}
}

.wx {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 20rpx;
	background-color: #fff;

	&::after {
		border: none !important;
	}
}
</style>
